<template>
	<view class="u-m-t-20">
		<LocationHeader :searchKeyword.sync="searchKeyword" @getSearchLeader="getSearchLeader"></LocationHeader>
		<u-gap height="20"></u-gap>
		<!-- 地图 -->
		<!-- show-location 显示带有方向的当前定位点 -->
		<map 
		id="pickUpLocationMap" 
		:scale="scale"
		:latitude="covers[0].latitude"
		:longitude="covers[0].longitude"
		:markers="covers"
		 @markertap="mapMarkertap"
		class="bf-location-map" show-location></map>
		<!-- 提货点列表 -->
		<view class="bf-location">
			<scroll-view scroll-y  
			@scrolltolower="loadMore"  
			:scroll-into-view="`map-${markerId}`"
			 scroll-with-animation
			class="bf-location-scroll u-m-t-10">
				<block v-if="searchResult.content.length>0">
					<view class="u-m-b-20" v-for="(item,index) in searchResult.content" :key="item.id">
						<PickUpLocationItem 
						:location="item" 
						:isCurrent="checkIsCurrent(item.id)"
						:id="`map-${item.id}`"
						@selectPickUpLocation="selectPickUpLocation"
						 :selected="markerId === item.id"> </PickUpLocationItem>
					</view>
				</block>
			</scroll-view>
		</view>
		<!-- 按钮 -->
		<!-- 这里待完善 -->
		<u-button type="warning">确定选择当前提货点</u-button>
	</view>
</template>

<script>
	import {mapActions,mapState,mapGetters} from "vuex"
	export default {
		data() {
			return {
				searchKeyword:"北京",
				filter: {
					page: 1, // 当前页码
					limit: 5, // 每页记录数
					latitude: '', // 经度
					longitude: '', // 纬度
				},
				searchResult: {
					content: [], // 搜索的结果
					last: false, // 是否已经最后
				},
				scale: 12, // 缩放尺寸
				      markerId: 0, // 当前选中标记
				      covers: [
						  //标记点信息 要根据经纬度画标记点
				        {
				          latitude: 39.909,
				          longitude: 116.39742,
				          iconPath: '/static/images/location.png',
				          width: 30,
				          height: 30,
				        },
				      ],
			};
		},
		computed:{
			// 导入当前提货点的信息
			 ...mapState('pickUpLocationModule', ['leaderAddressVo']),
			 // 导入选择提货点的状态值
			    ...mapGetters('pickUpLocationModule', ['checkIsCurrent']),
		},
		methods:{
			//重置提货点
			...mapActions("pickUpLocationModule",["selectLeaderAddressVoAction"]),
			//加载更多数据
			 loadMore(){
				 if(!this.searchResult.last){
					 //如果不是最后页的数据，页数加一，重新发送请求
					 this.filter.page +=1
					 this.getSearchLeader()//这种情况就是经纬度和之前一样了
				 }
			 },
			 //获取对应经纬度城市的所有提货点
			 async getSearchLeader(data) {
				 //该事件是由locationHeader子组件emit触发 所以data是通过子组件传递的
			 	if(data){
			 		// 重置一下searchReasult和filter的数据(否则获取的还是之前的区域？)
			 		Object.assign(this.$data.searchResult,this.$options.data().searchResult)
			 		Object.assign(this.$data.filter,this.$options.data().filter)
			 	}
			 	//如果有经纬度 覆盖filter 否则还是原来的filter 防止下拉加载的时候找不到对应的经纬度
			 	this.filter.latitude = data?data.latitude:this.filter.latitude
			 	this.filter.longitude = data?data.longitude:this.filter.longitude
			 	//封装要用来请求的对象
			 	const o = {
			 		...this.filter
			 	};
			 	//console.log(o)
			 	let res = await this.$u.api.getSearchLeader(o)
			 	this.searchResult ={
			 		...res,
			 		//追加合并数据 这是使用的是扩展运算符
			 		content:[...this.searchResult.content,...res.content]
			 	}
				//mark标记点的位置
				if(this.searchResult.content.length>0){
					let cover = []
					this.searchResult.content.map(item=>{
						cover.push({
							id:item.id,//后续标记点选择依靠这一点
							latitude: item.location.lat,
							longitude: item.location.lon,
							iconPath: '/static/images/location.png',
							width: 30,
							height: 30,
						})
					})
					//将所有整理过的cover复制给data的covers
					this.covers = cover;
					//将第一个covers的数据给地图
					let latitude = this.searchResult.content[0].location.lat;
					let longitude = this.searchResult.content[0].location.lon;
					//移动到对应的点
					this.mapctx.moveToLocation({
						latitude,longitude
					})
					this.scale = 12
					
				}
			 },
			 //点击标记点 
			 mapMarkertap(e){
				 // console.log(e.markerId);
				 this.markerId = e.markerId
			 },
			 //重新选择提货点
			 selectPickUpLocation(leaderId){
				 this.selectLeaderAddressVoAction({ leaderId });
			 }
		},
		onReady(e){
			//添加一个地图单例 该单例和map组件绑定
			this.mapctx = uni.createMapContext("pickUpLocationMap")
		},
		mounted(){
			uni.getLocation({
				type:"gcj02",
				success:async (res)=>{
				  this.covers[0]['latitude'] = res.latitude;
				   this.covers[0]['longitude'] = res.longitude;
				  //  console.log(this.covers);
					//通过网页接口（浏览器api）获取对应的地址信息
					//会报Unhandled promise rejection错误，可以使用trycatch解决
						//使用接口获取地址 接口封装的有自己的网页接口ak
						const {result} = await this.$u.api.getBaiduMapAddress({
						            latitude: res.latitude,
						            longitude: res.longitude,
						})
						this.searchKeyword = result.formatted_address
				}
			})
		}
	}
</script>

<style lang="scss" scoped>
.bf{
	 display: flex;
	  flex-direction: column;
	// 地图
	
	&-location-map{
		width: 100%;
		  height: calc(100vh - 120rpx - 400rpx - 140rpx);
	}
	// 滚动
	&-location{
		padding:20rpx;
		&-scroll{
			 height: 400rpx;
		}
	}
	
}
</style>
